<template>
  <div class="user-platform views-container">
    <div class="wlm-table">
      <!-- 结算弹窗 -->
      <el-dialog :visible.sync="dialogTableVisible" custom-class="reset-pwd wlm-form-dialog dialog-table" >
        <div class="wlm-form" v-if="dialogTableVisible">
            <div class="wlm-form-header wlm-dialog-fixheader">
                <span class="wlm-dialog-inlenr">选择结算门店</span>
            </div>
            <el-scrollbar wrap-class="scrollbar-wrapper">
                <div class="wlm-form-content">
                    <div class="wlm-dialog-main">
                        <div class="wlm-dialog-content">
                          <!-- @select="handle" -->
                               <el-table :data="storeData"  @selection-change="handle" ref="multipleTable" >
                                  <!-- <el-table-column type="selection" width="55">
                                  </el-table-column> -->
                                    <el-table-column prop="selection" label width="55">
                                      <template slot-scope="scope">
                                        <el-checkbox v-model="scope.row.checked" @change="handleSelectiondata(scope.row)"></el-checkbox>
                                      </template>
                                    </el-table-column>
                                    <el-table-column property="id" label="门店ID" >
                                    </el-table-column>
                                    <el-table-column property="name" label="门店名称"></el-table-column>
                              </el-table>
                               <div class="pagination-content flex-row flex-justify-b flex-align-c" style="margin-left:10px;">
                                  <el-row class="pagination-btns">
                                    <el-checkbox class="check-all" v-model="chek" @change="handbtn">全部</el-checkbox>
                                  </el-row>
                               </div>
                        </div>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <footer class="flex-row flex-align-c flex-justify-c wlm-dialog-fixfooter">
            <el-button size="small" type="primary" @click="formFormbtn">确定</el-button>
        </footer>
    </el-dialog>
      <div class="wlm-table-notice warning">
        <div class="flex-row flex-justify-b flex-align-c">
          <p>核销商品订单会在商品核销完成时生成账单，自提商品订单会在商品自提完成时生成账单，快递商品订单会在完成无法发起售后时生成账单</p>
        </div>
      </div>
      <div class="wlm-table-content" style="position: relative;">
        <div style="position: absolute;top:0;right:0;z-index:2;">
          <el-select v-model="tableFormatData.userTable.files.year" placeholder="请选择" @change="filesSerch">
            <el-option v-for="item in getYearsList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <el-select v-if="tableFormatData.userTable.files.type=='1'" v-model="tableFormatData.userTable.files.month" placeholder="请选择" @change="filesSerch">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
        <el-tabs v-model="tableFormatData.userTable.files.type" type="card" @tab-click="filesSerch">
          <!-- @tab-click="filesSerch" -->
          <el-tab-pane label="日账单" name="1"></el-tab-pane>
          <el-tab-pane label="月账单" name="2"></el-tab-pane>
        </el-tabs>
        <el-table :ref="tableFormatData.userTable.key" :data="tableFormatData.userTable.tableData" @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="date" label="日期">
            <template slot-scope="scope">
              <!-- <span v-if="tableFormatData.userTable.files.type=='1'">{{new Date(scope.row.createTime).getTime()| parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
                        <span v-if="tableFormatData.userTable.files.type=='2'">{{new Date(scope.row.createTime).getTime()| parseTime('{y}-{m}')}}</span> -->
              <span v-if="tableFormatData.userTable.files.type=='1'">{{scope.row.createTime}}</span>
              <span v-if="tableFormatData.userTable.files.type=='2'">{{scope.row.createTime}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="商家名称">
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="入账数量">
            <template slot-scope="scope">
              <el-tag type="danger">{{scope.row.number}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" :label="this.tableFormatData.userTable.otherData.data_mode==1?'销售金额':'入账金额'">
            <template slot-scope="scope">
              <span>{{scope.row.money}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="状态">
            <template slot-scope="scope">
              <el-tag type="info">未结算：{{scope.row.sum1}}</el-tag>
              <el-tag type="success">已结算：{{scope.row.sum2}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <div class="operation-group">
                <router-link v-if="tableFormatData.userTable.files.type=='2'" class="wlm-text" tag="a" target="_blank" :to="{path:'/merchant/merchantSettlementBillDetail', query:{
                  type:tableFormatData.userTable.files.type,year:new Date(scope.row.createTime).getFullYear(),month:new Date(scope.row.createTime).getMonth()+1,id:$route.query.id,
                  store_user_id:$route.query.store_user_id?$route.query.store_user_id:'',
                  h_aid:$route.query.h_aid?$route.query.h_aid:'',}}">
                  <el-button type="text">详情</el-button>
                </router-link>
                <router-link v-if="tableFormatData.userTable.files.type=='1'" class="wlm-text" tag="a" target="_blank" :to="{path:'/merchant/merchantSettlementBillDetail', query:{type:tableFormatData.userTable.files.type,year:new Date(scope.row.createTime).getFullYear(),month:new Date(scope.row.createTime).getMonth()+1,day:new Date(scope.row.createTime).getDate(),id:$route.query.id,
                store_user_id:$route.query.store_user_id?$route.query.store_user_id:'',
                  h_aid:$route.query.h_aid?$route.query.h_aid:'',}}">
                  <el-button type="text">详情</el-button>
                </router-link>
                <div class="btn-line"></div>
                <el-button class="wlm-text" type="text" :data-query="JSON.stringify({type:tableFormatData.userTable.files.type, year:new Date(scope.row.createTime).getFullYear(),month:new Date(scope.row.createTime).getMonth()+1,day:tableFormatData.userTable.files.type=='1'? new Date(scope.row.createTime).getDate() : [],id: $route.query.id})" v-exceldown="{path:'getBillDetail&',query: { export: 1 , get_status: 2}}">{{ $t('excel.export') }}列表</el-button>
                <div v-if="scope.row.status==1" class="btn-line"></div>
                <!-- <el-button v-if="scope.row.status==1" @click="changeTableItem(
                  {ids:[$route.query.id],type:tableFormatData.userTable.files.type,startTime:scope.row.createTime,endTime:scope.row.createTime}
                  ,tableFormatData.userTable.change.restore,{isWarning: true,warning:'是否结算账单？',cancel:'已取消'})" class="wlm-text" type="text">结算</el-button> -->
                   <el-button v-if="scope.row.status==1" @click="changbtn({ids:[$route.query.id],type:tableFormatData.userTable.files.type,startTime:scope.row.createTime,endTime:scope.row.createTime})" class="wlm-text" type="text">结算</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-content flex-row flex-justify-b flex-align-c">
          <el-row class="pagination-btns">
            <el-checkbox class="check-all" true-label="1" false-label="0" v-model="tableFormatData.userTable.files.checkall" @change="toggleSelection">全部</el-checkbox>
           <el-button @click="changbtn({ids:[$route.query.id],type:tableFormatData.userTable.files.type,startTime:maxTime,endTime:minTime})" :disabled="isGroup" size="mini" class="wlm-text" type="primary">批量结算</el-button>
            <!-- <el-button @click="changeTableItem(
              {ids:[$route.query.id],type:tableFormatData.userTable.files.type,startTime:maxTime,endTime:minTime}
              ,tableFormatData.userTable.change.restore,{isWarning: true,warning:'是否结算账单？',cancel:'已取消'})" size="mini" class="wlm-text" type="primary">批量结算</el-button> -->
          </el-row>
          <el-pagination :disabled="!hasTableData" @size-change="listPageChange" @current-change="listPageChange" :current-page.sync="tableFormatData.userTable.pagination.page" :page-sizes="tableFormatData.userTable.pagination.pagesizes" :page-size.sync="tableFormatData.userTable.pagination.list_rows" layout="total, sizes, prev, pager, next, jumper" :total="hasTableData?tableFormatData.userTable.pagination.total : 0">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getBillInfoList,
  setBusinessSettlement,
  shopIndex
} from '@/api/merchant'
import exceldown from '@/directive/exceldown'
import mixins from '@/mixins/mixins'
export default {
  mixins: [mixins.getters('Table')],
  name: 'MerchantSettlementBill',
  components: {
  },
  computed: {
    scopeTime() {
      const table = this.tableFormatData.userTable.files.ids
      const result = []
      if (table.length > 0) {
        table.map(item => {
          result.push(new Date(item.createTime).getTime())
        })
      }

      return result.sort((a, b) => { return a - b })
    },
    maxTime() {
      return `${new Date(this.scopeTime[0]).getFullYear()}-${`${new Date(this.scopeTime[0]).getMonth() + 1}`.padStart(2, '0')}-${`${new Date(this.scopeTime[0]).getDate()}`.padStart(2, '0')}` || ''
    },
    minTime() {
      return `${new Date(this.scopeTime[this.scopeTime.length - 1]).getFullYear()}-${`${new Date(this.scopeTime[this.scopeTime.length - 1]).getMonth() + 1}`.padStart(2, '0')}-${`${new Date(this.scopeTime[this.scopeTime.length - 1]).getDate()}`.padStart(2, '0')}` || ''
    },
    getYearsList() {
      const yearsStart = 2018
      const yearsList = []
      const currentYear = new Date().getFullYear()
      const yearsLength = currentYear - yearsStart
      for (let i = 0, yearItem = {}; i <= yearsLength; i++) {
        yearItem = {
          lable: yearsStart + i + '',
          value: yearsStart + i
        }
        yearsList.push(yearItem)
      }
      return yearsList
    }
  },
  data() {
    return {
      selectInitty:true,
      options: [{
        value: 1,
        label: '1月'
      }, {
        value: 2,
        label: '2月'
      }, {
        value: 3,
        label: '3月'
      }, {
        value: 4,
        label: '4月'
      }, {
        value: 5,
        label: '5月'
      }, {
        value: 6,
        label: '6月'
      }, {
        value: 7,
        label: '7月'
      }, {
        value: 8,
        label: '8月'
      }, {
        value: 9,
        label: '9月'
      }, {
        value: 10,
        label: '10月'
      }, {
        value: 11,
        label: '11月'
      }, {
        value: 12,
        label: '12月'
      }],
      dialogTableVisible:false,
      blogTitle: '',
      chek:true,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: getBillInfoList
            //   delList: userListDel,
          },
          tableData: [],
          otherData:{},
          files: {
            month: new Date().getMonth() + 1,
            year: new Date().getFullYear(),
            type: '1',
            ids: [],
            checkall: '0',
            Recycle: '1',
            checkalls:'0'
            // redirect: 'business_settlement_id'
          },
          change: {
            restore: {
              name: '结算',
              key: 'restore',
              api: setBusinessSettlement
            }
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      },
      store_id:[],
      obj:{},
      storeData:[
        {
          id:-1,
          name:'管理员核销',
          checked:true,
        }
      ],
    }
  },
  directives: {
    exceldown
  },
  created(){
  },
  methods: {
    handbtn(){
      console.log('this.storeData',this.chek);
      this.storeData.map((item,index) => {
         this.$set(this.storeData[index],'checked',this.chek)
        })
        console.log(' this.storeData', this.storeData,this.chek);
    },
    handle(selection) {
      this.store_id = [];
     selection.map(item => {
       this.store_id.indexOf(item.id) == -1 && this.store_id.push(item.id);
     });
    //  store_id[] = row.id;
    },

    changbtn(obj){
      this.obj = obj;
      this.store_id = [];
      // console.log('obj',obj);
      this.storeData = [
        {
          id:-1,
          name:'管理员未选择门店核销或后台核销'
        }
      ];
      this.dialogTableVisible = true
      shopIndex({bus_id:this.$route.query.id,is_page: '2'}).then(res=>{
        this.storeData.push(...res.data.data);
        this.storeData.map((item,index) => {
          // this.storeData[index] = {...item,checked:true};
         this.$set(this.storeData[index],'checked',true)
        })
        
        console.log("11111111111111111",this.storeData)
      })
    },
// changeTableItem({ids:[$route.query.id],type:tableFormatData.userTable.files.type,startTime:maxTime,endTime:minTime}
    formFormbtn(obj){

      this.store_id = [];
      this.storeData.map(item => {
          item.checked && this.store_id.push(item.id);
      })

      console.log('obj1',obj,this.store_id);
// return;
      setBusinessSettlement({store_id:this.store_id,...this.obj}).then(res=>{
        if(res.data.code == 1){
          this.$message.success('结算成功！');
          // this.obj = {};
          this.store_id = [];
          this.dialogTableVisible = false
          this.filesSerch()
        }else{
          this.$message.error(res.data.msg);
        }
      })
    },
    handleSelectiondata(row){
      row = {...row,checked:!row.checked};
    }
  }
}
</script>

<style lang="scss" scoped>
.user-platform {
}
</style>
